package org.fxcontainer.utils
{

	import mx.managers.BrowserManager;
	import mx.managers.IBrowserManager;
	import org.fxcontainer.commands.navigation.chain.ControlURL;

	/**
	 * The URL processor class - incapsulates resolving significant parts from URL.
	 * @author Izzet_Mustafayev
	 */
	public final class URLProcessor
	{

		/**
		 * The constant of the control place in URL.
		 */
		private static const CONTROL_PLC:int=1;

		/**
		 * The constant of the page place in URL.
		 */
		private static const PAGE_PLC:int=0;

		/**
		 * Creates <code>URLProcessor</code> instance.
		 */
		public function URLProcessor()
		{
			super();
			this.fragments=this.resolveFragments();
		}

		/**
		 * Holds current URL fragments.
		 */
		private var fragments:Array;

		/**
		 * Determins whether URL was specified for the on same page navigation.
		 * @return true if navigation is within page scope, false otherwise
		 */
		public function isOnPage():Boolean
		{
			return this.fragments.indexOf('/') == 0;
		}

		/**
		 * Resolves controls from URL fragment.
		 * @return the controls to invoke
		 */
		public function resolveControls():Array
		{
			var resControls:Array=new Array();
			var controlURL:String=fragments[CONTROL_PLC];
			if (controlURL)
			{
				controlURL=controlURL.replace("{", "");
				controlURL=controlURL.replace("}", "");
				var controls:Array=clearNulls(controlURL.split(";;"));
				for (var c:int=0; c < controls.length; c++)
				{
					var controlAttrs:Array=clearNulls(String(controls[c]).split("::"));
					var methodArgs:Array=controlAttrs[2] != null ? clearNulls(String(controlAttrs[2]).split("||")) : null;
					var control:ControlURL=new ControlURL(controlAttrs[0], controlAttrs[1] != null ? controlAttrs[1] : null, methodArgs);
					resControls.push(control);
				}
			}

			return resControls;
		}

		/**
		 * Resolves page name from URL fragment.
		 * @return the page name
		 */
		public function resolvePage():String
		{
			return this.fragments[PAGE_PLC];
		}

		private function clearNulls(values:Array):Array
		{
			var result:Array=new Array();
			if (!values)
			{
				for (var i:int=0; i < values.length; i++)
				{
					var value:*=values[i];
					if (value && (value is String && String(value).length > 1))
					{
						result.push(value);
					}
				}
			}
			return result;
		}

		/**
		 * Resolves URL frgaments of the current broswer address bar state.
		 * @return the array of fragments separated by "/" symbol
		 */
		private function resolveFragments():Array
		{
			var browserManager:IBrowserManager=BrowserManager.getInstance();
			var urlFragment:String=browserManager.fragment;
			return this.clearNulls(urlFragment.split("/"));
		}

	}
}